package com.cmpe.av;

import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.io.PrintWriter; 

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.MultipartStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.cmpe.av.logic.ReportLogic;
import com.cmpe.av.logic.UserLogic;
import com.cmpe.av.model.ObstacleType;
import com.cmpe.av.model.Report;
import com.cmpe.av.model.Tag;
//import com.oreilly.servlet.MultipartRequest;
/**
 * Servlet implementation class SearchPage
 */
@WebServlet("/SearchPage")
public class SearchPage extends HttpServlet {

	private List<Tag> tags=getTags();
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SearchPage() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		ArrayList reportOrder = new ArrayList() ;
		HttpSession session = request.getSession();

		String strErrMsg = null;
		ReportLogic msAccess;
		List<Report> reports = new ArrayList<Report>();
		String allLat,allLng,allNames,allIDs,allStatus;
		int reportSize;
		if(request.getParameter("by")!=null){


			if(Integer.parseInt(request.getParameter("by"))==0)
				reports= (List<Report>) session.getAttribute("reportsByDate");
			else
				reports = (List<Report>) session.getAttribute("reportsByRank");

			if(reports.size()!=0)
				request.setAttribute("valid", true);

			request.setAttribute("reports", reports);
			reportSize = reports.size();
			allLat = createAllLatString(reports);
			allLng = createAllLngString(reports);
			allNames = createAllNamesString(reports);
			allIDs = createAllIDsString(reports);
			allStatus = createAllStatusString(reports);

			request.setAttribute("allLat", allLat);
			request.setAttribute("allLng", allLng);
			request.setAttribute("allNames", allNames);
			request.setAttribute("allIDs", allIDs);
			request.setAttribute("allStatus", allStatus);
			request.setAttribute("reportSize", reportSize);
			request.getRequestDispatcher("searchPage.jsp").forward(request,response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		ArrayList reportOrder = new ArrayList() ;
		String reportStatus = request.getParameter("reportStatus");
		//	System.out.println("report status is" + reportStatus);
		String location = request.getParameter("location");
		String type = request.getParameter("obstacleType");
		String tag = request.getParameter("tag");
		HttpSession session = request.getSession();

		String strErrMsg = null;
		ReportLogic msAccess;
		List<Report> reportsByDate= new ArrayList<Report>();
		List<Report> reportsByRank= new ArrayList<Report>();
		String lat, lng;
		String allLat,allLng,allNames,allIDs,allStatus;
		int reportSize;
		double latitude=0.0, longitude=0.0;
		//List<Double> lat_mark = new ArrayList<Double>();
		//List<Double> lon_mark = new ArrayList<Double>();

		lat = request.getParameter("locationFieldLat");
		lng = request.getParameter("locationFieldLong");

		if (!lat.isEmpty() && !lng.isEmpty()){
			latitude = Double.parseDouble(lat);
			longitude = Double.parseDouble(lng);
		}

		PrintWriter out = response.getWriter();
		if (request.getParameter("button").equals("Search")){

			try{
				msAccess = new ReportLogic(); 
				if(type.equals("null") && lat.isEmpty() && tag.equals("null") && reportStatus.equals("null"))
					request.setAttribute("invalid", true);
				else{
					reportsByDate = msAccess.searchReport(type, latitude, longitude, tag, reportStatus,0);
					reportsByRank = msAccess.searchReport(type, latitude, longitude, tag, reportStatus,1);
				}


				if(reportsByDate.size()!=0)
					request.setAttribute("valid", true);
				else
					request.setAttribute("noReport", true);
				reportSize = reportsByDate.size();
				allLat = createAllLatString(reportsByDate);
				allLng = createAllLngString(reportsByDate);
				allNames = createAllNamesString(reportsByDate);
				allIDs = createAllIDsString(reportsByDate);
				allStatus = createAllStatusString(reportsByDate);

				request.setAttribute("allLat", allLat);
				request.setAttribute("allLng", allLng);
				request.setAttribute("allNames", allNames);
				request.setAttribute("allIDs", allIDs);
				request.setAttribute("allStatus", allStatus);
				request.setAttribute("reports", reportsByDate);
				session.setAttribute("reportsByDate", reportsByDate);
				session.setAttribute("reportsByRank", reportsByRank);
				request.setAttribute("reportSize", reportSize);
				request.getRequestDispatcher("searchPage.jsp").forward(request,response);
			}
			catch (Exception e) {
				strErrMsg = "Cannot be submitted. Please try again.";
				System.out.println(e);
			}
		}
		else if (request.getParameter("button").equals("Login")){

			UserLogic user;
			String userName = request.getParameter("name");
			String passWord = request.getParameter("password");
			strErrMsg = null;
			session = request.getSession();
			int userID = -1;
			// response.
			try {
				user = new UserLogic();

				userID = user.getUserID(userName, passWord);
				if (userID != -1) {
					session.setAttribute("userName", userName);
					session.setAttribute("loggedin", true);
					session.setAttribute("userID", userID);

					response.setHeader("Cache-Control","no-cache"); 
					response.setHeader("Pragma","no-cache"); 
					response.setDateHeader ("Expires", 0); 
					response.setHeader("Cache-Control", "no-store");

					request.getRequestDispatcher("searchPage.jsp").forward(
							request, response);
				} else {
					request.setAttribute("invalidLogin", true);
					request.getRequestDispatcher("searchPage.jsp").forward(request,
							response);	
				}
			} 

			catch (Exception e) {
				strErrMsg = "Unable to validate user / password in database";
				System.out.println(e);
			}


		}
		else if (request.getParameter("button").equals("Logout")){
			session = request.getSession(false); 
			session.removeAttribute("userName");
			session.invalidate();
			response.sendRedirect("searchPage.jsp");
		}

		else if(request.getParameter("button").equals("Not A Member?")){
			response.sendRedirect("default.jsp");

		}

	}

	public List<Tag> getTags(){
		ReportLogic msAccess;
		tags= new ArrayList<Tag>();
		try{
			msAccess = new ReportLogic();
			tags=msAccess.getTags();
		}
		catch(Exception e){
			System.out.println(e);
		}
		return tags;
	}
	public String createAllLatString(List<Report> reports){
		List<String> lats = new ArrayList<String>();
		for(int i=0;i<reports.size();i++){
			lats.add(Double.toString(reports.get(i).getLatitude()));
		}
		StringBuilder builder = new StringBuilder();

		for (String string : lats) {
			if (builder.length() > 0) {
				builder.append(" ");
			}
			builder.append(string);
		}
		String lat = builder.toString();
		return lat;
	}

	public String createAllLngString(List<Report> reports){
		List<String> lngs = new ArrayList<String>();
		for(int i=0;i<reports.size();i++){
			lngs.add(Double.toString(reports.get(i).getLongitude()));
		}
		StringBuilder builder = new StringBuilder();

		for (String string : lngs) {
			if (builder.length() > 0) {
				builder.append(" ");
			}
			builder.append(string);
		}
		String lng = builder.toString();
		return lng;
	}

	public String createAllNamesString(List<Report> reports){
		List<String> names = new ArrayList<String>();
		for(int i=0;i<reports.size();i++){
			names.add(reports.get(i).getReportName());
		}
		StringBuilder builder = new StringBuilder();

		for (String string : names) {
			if (builder.length() > 0) {
				builder.append("---");
			}
			builder.append(string);
		}
		String name = builder.toString();
		return name;
	}

	public String createAllIDsString(List<Report> reports){
		List<String> IDs = new ArrayList<String>();
		for(int i=0;i<reports.size();i++){
			IDs.add(Long.toString(reports.get(i).getReport_id()));
		}
		StringBuilder builder = new StringBuilder();

		for (String string : IDs) {
			if (builder.length() > 0) {
				builder.append("---");
			}
			builder.append(string);
		}
		String ID = builder.toString();
		return ID;
	}

	public String createAllStatusString(List<Report> reports){
		List<String> Status = new ArrayList<String>();
		for(int i=0;i<reports.size();i++){
			Status.add(Integer.toString(reports.get(i).getStatus()));
		}
		StringBuilder builder = new StringBuilder();

		for (String string : Status) {
			if (builder.length() > 0) {
				builder.append("---");
			}
			builder.append(string);
		}
		String State = builder.toString();
		return State;
	}
}